﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using Microsoft.Reporting.WebForms;
using System.IO;
using System.Data;
using IQKS.AWP.BusinessAccessLayer;
using IQKS.AWP.BusinessObject;

public partial class Candidate_AccreditationCandidateResultEmail : System.Web.UI.Page
{
    Int32 candidateId;
    protected void Page_Load(object sender, EventArgs e)
    {
        candidateId = Convert.ToInt32(Request.QueryString["CandidateId"]);
        //if (!IsPostBack)
        //{
            
            GetCandidateDetailsDataSet(candidateId);
        //} 

    }
    private DataSet GetCandidateDetailsDataSet(int cid)
    {
        DataSet objDs = null;
        DataSet objEmail = null;
        try
        {

            objDs = new UserMasterBAL().GetCandidatedetailReg(cid);
            //string strUserRole = CommonUtility.GetCurrentUserRole();
            RegistrationNo.Text = Convert.ToString( objDs.Tables[0].Rows[0]["RegistrationNo"]);
            CandidateName.Text = Convert.ToString(objDs.Tables[0].Rows[0]["FirstName"]) +" " + Convert.ToString(objDs.Tables[0].Rows[0]["LastName"]);
            EmailId.Text = Convert.ToString(objDs.Tables[0].Rows[0]["Email"]);            
            
            //Load email document            
            objEmail = new CandidateResultEmailBAL().GetCandidateResultEmail(cid);
            EmailCounter.Text = Convert.ToString(objEmail.Tables[0].Rows[0]["EmailSentCounter"]);
            if (EmailCounter.Text != "" && EmailCounter.Text != string.Empty)
            {
                BtnSendEmail.Enabled = true;
            }
            else
            {
                BtnSendEmail.Enabled = false;
            }
            if (objEmail.Tables[1].Rows.Count > 0)
            {
                DataTable dt = objEmail.Tables[1];
                gvResultEmailDocs.DataSource = dt; // objEmail.Tables[1];
                gvResultEmailDocs.DataBind();
            }
            
        }
        catch (Exception exception)
        {
            exception.AddErrorToLog(); //throw new ApplicationException(exception.Message);
        }
        return objDs;
    }
    public string GetDocumentDownload(object objReviewDocumentFile)
    {
        string strPathReviewDoc = string.Empty;
        strPathReviewDoc =  Convert.ToString(objReviewDocumentFile);       
        strPathReviewDoc = "javascript:onClickLink('" + strPathReviewDoc.Replace("~", "..") + "')";
        return strPathReviewDoc;
    }
    /*public string GetBriefDownload(object objDocumentFile)
    {
        string strPath = string.Empty;
        strPath = Convert.ToString(ConfigurationSettings.AppSettings["BriefDoc"]) + Convert.ToString(objDocumentFile);
        strPath = "javascript:onClickLink('" + strPath.Replace("~", "..") + "')";
        return strPath;
    }*/


    public string SaveResultLetterPDF()
    {
        string savePath = "";
        string appLog = MapPath(Convert.ToString(ConfigurationManager.AppSettings["LogFile"]));
        try {
            
            //string savePath = Server.MapPath("~") + "\\upload\\ResultLetter\\" + RegistrationNo.Text + ".pdf";
            string strPath = MapPath(Convert.ToString(ConfigurationManager.AppSettings["ResultLetterPath"]));
            savePath = strPath + RegistrationNo.Text + ".pdf";
            CommonUtility.WriteErrorLog(appLog, "SaveResultLeterPDF path:" + savePath);
            string DataSetName = "GetCandidateResultLetter";
            // Setup the report viewer object and get the array of bytes
            ReportViewer viewer = new ReportViewer();
            viewer.ProcessingMode = ProcessingMode.Local;
            viewer.LocalReport.ReportPath = Server.MapPath("~") + "\\report\\CandidateResult.rdlc";
            // ObjectDataSource1.SelectParameters.Add(new Parameter("CandidateId"));
            ReportDataSource datasource = new ReportDataSource(DataSetName, ObjectDataSource1);
            viewer.LocalReport.DataSources.Clear();
            ObjectDataSource1.DataBind();
            viewer.LocalReport.DataSources.Add(datasource);
            byte[] Bytes = viewer.LocalReport.Render(format: "PDF", deviceInfo: "");
            CommonUtility.WriteErrorLog(appLog, "SaveResultLeterPDF PDF Generated");

            using (FileStream stream = new FileStream(savePath, FileMode.Create))
            {
                stream.Write(Bytes, 0, Bytes.Length);
            }
            CommonUtility.WriteErrorLog(appLog, "SaveResultLeterPDF saved");
            savePath = "~//upload//ResultLetter//" + RegistrationNo.Text + ".pdf";
          
        }
        catch (Exception ex)
        {
            CommonUtility.WriteErrorLog(appLog, "SaveResultLeterPDF Error" + ex.Message);
            savePath = "Error";
        }
        finally
        {
            
        }
        return savePath;
    }

    protected void BtnUploadCovertingLetter_Click(object sender, EventArgs e)
    {
        /*
        if (EmailCounter.Text == null || EmailCounter.Text == "")
        {
            //string resultLetterPath;
            //resultLetterPath = SaveResultLetterPDF();
            string strPath = string.Empty;
            string strFileExt = string.Empty;
            string strFileName = string.Empty;
            string strRetVlu = string.Empty;
            string strCoverLeterFilePath = string.Empty;
            string strResultLetterPath = string.Empty;
            string strResultLetterPath1 = string.Empty;


            strFileExt = Path.GetExtension(FUCoveringLetter.PostedFile.FileName);
            strFileName = Path.GetFileNameWithoutExtension(FUCoveringLetter.FileName);
            strPath = Server.MapPath("~") + "\\upload\\CoveringLetter\\" + RegistrationNo.Text + strFileExt;
            strCoverLeterFilePath =  "~//upload//CoveringLetter//" + RegistrationNo.Text; //+ strFileExt;

            //string appPath = Server.MapPath("~") + "upload\\review\\";
            string appPath = "~//upload//review//";

            CandidateResultEmailBAL objCREBAL = new CandidateResultEmailBAL();
            strRetVlu = (string)objCREBAL.SetResultEmail("INSERT",
                                            appPath,
                                            candidateId, 
                                            CommonUtility.GetLoggedOnUserId(), 
                                            CommonUtility.GetLoggedOnUserId(),
                                            DateTime.Now);
            if (strRetVlu != "ERROR")
            {
                //Covering Letter document type id =12
                
                strCoverLeterFilePath = (string)objCREBAL.SetResultEmailDocument(candidateId,12, strCoverLeterFilePath, strFileExt,"Y");
                if(strCoverLeterFilePath != "ERROR")
                {                    
                    FUCoveringLetter.SaveAs( strPath);
                    //strCoverLeterFilePath = "~//upload//CoveringLetter//" + RegistrationNo.Text; //+ strFileExt;
                    strResultLetterPath = SaveResultLetterPDF();
                    //Result Letter document type id =11
                    strResultLetterPath1 = (string)objCREBAL.SetResultEmailDocument(candidateId, 11, strResultLetterPath, "","Y");
                    if (strResultLetterPath1 != "ERROR")
                    {
                        //here refresh grid to show all document
                        GetCandidateDetailsDataSet(candidateId);


                    }

                }

            }
            
        /*CandidateBriefDetailBAL objCBDBAL = new CandidateBriefDetailBAL();
            strFileName = (string)objCBDBAL.SetCandidateBriefDocument(CommonUtility.GetLoggedOnUserId(), Convert.ToInt32(hdnCandidateBriefId.Value), Convert.ToInt32(hdnCandidateID.Value), Convert.ToInt16(hdnBriefID.Value), Convert.ToInt16(hdnCandidateStatus.Value), 1, strFileName, strFileExt, txtComments.Text.Trim());
            if (strFileName != "ERROR")
            {
                filProposal.SaveAs(strPath + strFileName);
                gvProposalDocument.DataSource = objCBDBAL.GetCandidateBriefDocumentByDocumentType(1, Convert.ToInt32(hdnCandidateID.Value), Convert.ToInt16(hdnBriefID.Value));
                gvProposalDocument.DataBind();
            }
            * /
         }
        */
    }

    /* protected void gvResultEmailDocs_RowDataBound(object sender, GridViewRowEventArgs e)
     {
         if (e.Row.RowType == DataControlRowType.DataRow)
         {
             LinkButton lnkButton = (LinkButton)e.Row.FindControl("Download");

             lnkButton.Attributes.Add("onclick", "javascript:return " + "confirm('Are you sure you want to Download?')");

         }

     }*/

    protected void BtnSendEmail_Click(object sender, EventArgs e)
    {
        CandidateResultEmailBAL objCREBAL = new CandidateResultEmailBAL();
        string strRetVlu = (string)objCREBAL.SetResultEmail("SEND",
                                        "",
                                        candidateId,
                                        CommonUtility.GetLoggedOnUserId(),
                                        CommonUtility.GetLoggedOnUserId(),
                                        DateTime.Now);
        if (strRetVlu != "ERROR")
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Email Submitted Successfully.');", true);
            GetCandidateDetailsDataSet(candidateId);
        }
    }

    protected void BtnGenerateDocs_Click(object sender, EventArgs e)
    {
        if (EmailCounter.Text == null || EmailCounter.Text == "")
        {   
            string strPath = string.Empty;
            string strFileExt = string.Empty;
            string strFileName = string.Empty;
            string strRetVlu = string.Empty;
            string strCoverLeterFilePath = string.Empty;
            string strResultLetterPath = string.Empty;
            string strResultLetterPath1 = string.Empty;
            
            string appPath = "~//upload//review//";

            CandidateResultEmailBAL objCREBAL = new CandidateResultEmailBAL();
            strRetVlu = (string)objCREBAL.SetResultEmail("INSERT",
                                            appPath,
                                            candidateId,
                                            CommonUtility.GetLoggedOnUserId(),
                                            CommonUtility.GetLoggedOnUserId(),
                                            DateTime.Now);
            if (strRetVlu != "ERROR")
            {
                strResultLetterPath = SaveResultLetterPDF();
                //Result Letter document type id =11
                strResultLetterPath1 = (string)objCREBAL.SetResultEmailDocument(candidateId, 11, strResultLetterPath, "", "Y");
                if (strResultLetterPath1 != "ERROR")
                {
                    //here refresh grid to show all document
                    GetCandidateDetailsDataSet(candidateId);

                }

            }
        }
    }
    
}
